import React from 'react';
import { Icon, RichEditor, Bubble } from 'weaver-mobile';
import { _, InputUtil } from '../../util/pcPublic';
import { getLabel } from '../../util/common';
import { getRemarkHtml } from '../../util/SignUtil';
import { withRouter } from 'react-router-dom';
import { CKTextarea } from 'weaver-mobile-page';
const trim = _.trim;
@withRouter
export default class WfTextarea extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			value: props.value ? props.value : "",
			isonfocus: false,
			ckTextareaStore: new CKTextarea.Store({ route: '/req', id: "ckTextarea_" + this.props.fieldMark })
		};
		this.inputRef = React.createRef();
	}
	componentWillReceiveProps(nextProps) {
		if (this.state.value !== nextProps.value) {
			this.setState({
				value: nextProps.value
			});
		}
	}
	componentWillUnmount() {
		const { viewAttr, isDetail, detailtype } = this.props;
		if (isDetail && viewAttr > 1 && detailtype !== 2 && this.state.isonfocus) {	//未失去焦点直接返回情况
			this.doBlurEvent();
		}
	}

	render() {
		let { value = "", isonfocus, ckTextareaStore } = this.state;
		let { fieldid, viewAttr, detailtype, textheight, length, fieldMark, emptyShowContent } = this.props;
		let isRequired = false;
		if (viewAttr !== 1) {
			let _value = value.replace(/<p>/ig, '').replace(/<\/p>/ig, '').replace(/ /ig, "").replace(/&nbsp;/ig, "").replace(/<br \/>/ig, "");
			isRequired = viewAttr === 3 && trim(_value).length === 0;
		}
		if (detailtype === 2) {		//富文本
			const swapClassName = `wf-req-richtext-item ${viewAttr === 1 ? "wf-richtext-view" : "wf-richtext-edit"}`;
			const height = 40 * textheight;
			return (
				<div className={swapClassName}>
					{
						viewAttr === 1 ?
							<div className="wf-richtext-view-text" dangerouslySetInnerHTML={{ __html: getRemarkHtml(value, false) }} />
							:
							<div className={`wf-richtext-edit-box${!isonfocus ? " wf-richtext-placeholder" : ""}`}>
								<CKTextarea
									id={fieldMark}
									store={ckTextareaStore}
									text={value}
									value={value}
									style={{ height: 200 }}
									config={{
										toolbar: [ // 自定义按钮配置
											{ name: 'styles', items: ['FontSize'] },//'Format', 'Font',
											{ name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] },
										],
									}}
									onChange={this.doRichTextChangeEvent.bind(this)}
									initDataCallback={() => {
										const { richEditorStore } = ckTextareaStore;
										const { editor } = richEditorStore;
										if (editor) {
											editor.focusManager && editor.focusManager.blur()
										}
									}}
									viewAttr={viewAttr}
									placeholder={emptyShowContent}
									richTextProps={{
										replyProps: {
											leftConfig: [
												{ type: 'voice' },
												// {type:'blog-biaoqing'},
												{ type: 'blog-tupian', model: 2 }
											]
										}
									}}
								/>
							</div>
					}
					<input type="hidden" id={fieldMark} name={fieldMark} value={value} />
				</div>
			)
		} else {
			const swapClassName = `wf-req-textarea-item wf-form-textarea ${viewAttr === 1 ? "wf-textarea-view" : "wf-textarea-edit"}`;

			if (viewAttr === 1) {
				return (
					<div className={swapClassName}>
						<div id={fieldMark + "span"} className="wf-textarea-view-box" dangerouslySetInnerHTML={{ __html: value }}></div>
						<input type="hidden" id={fieldMark} name={fieldMark} value={value} />
					</div>
				)
			} else {
				//支持可编辑无值时显示灰色默认值
				let styleInfo = {};
				emptyShowContent = emptyShowContent || "";
				if (!isonfocus && emptyShowContent !== "" && value === "") {
					styleInfo["color"] = "#868686";
					value = emptyShowContent;
				} else {
					styleInfo["color"] = "";
				}
				return (
					<div className={swapClassName} onClick={this.editClickEvent.bind(this)}>
						<textarea
							ref={this.inputRef}
							id={fieldMark}
							name={fieldMark}
							rows={textheight}
							className={`wf-textarea-edit-box wf-form-textarea-${fieldid}${!isonfocus ? " wf-textarea-placeholder" : ""}`}
							style={styleInfo}
							onFocus={this.doFocusEvent.bind(this)}
							onBlur={this.doBlurEvent.bind(this)}
							onChange={this.setTextAreaValue.bind(this)}
							value={value}
						/>
						<div className="wf-textarea-required-icon">
							{
								isRequired && <img src="/images/BacoError_wev9.png" align="absmiddle" />
							}
						</div>
						<div className="wf-textarea-edit-icon">
							<Icon type="editor-01" />
						</div>
					</div>
				)
			}
		}
	}
	editClickEvent() {
		const { isonfocus } = this.state;
		if (!isonfocus) {
			const elm = this.inputRef.current;
			elm.selectionStart = -1;	//光标置最后
			elm.focus();
		}
	}
	doFocusEvent(e) {
		this.setState({ isonfocus: true });
	}
	doBlurEvent(e) {
		const value = e ? e.target.value : this.state.value;
		this.setState({ isonfocus: false });
		this.props.onChange && this.props.onChange(value);
	}
	setTextAreaValue(e) {
		const { fieldlabel, fielddbtype } = this.props;
		let value = e.target.value;
		//text 不限制长度
		if ('text' !== fielddbtype) {
			let valLen = InputUtil.realLength(value);
			let length = 4000;
			let specialChar = value.match(/\"| /ig);
			if (specialChar)
				length = length - specialChar.length * 5;		//后台转译成6个字符
			specialChar = value.match(/&|<|>|\n/ig);
			if (specialChar)		//后台转译成4个字符
				length = length - specialChar.length * 3;
			if (length && valLen > length) {
				Bubble.warning(`${fieldlabel}${getLabel(386376, '字段值长度不能超过4000')}(${getLabel(124962, '1个中文字符等于3个长度')})`);
				value = InputUtil.checkLength(value, valLen, length);
			}
		}
		this.setState({ value: value });
	}
	doRichTextChangeEvent(value) {
		this.setState({ value: value });
		this.props.onChange && this.props.onChange(value);
	}
}
